package com.le.tester.imooc.oldfairy.basic;

import java.util.Objects;

/**
 * createTime：2023/5/18 15:44
 * description：
 */
public abstract class Try<T> {
    protected Try() {
    }

    public abstract boolean isSuccess();

    public abstract T get() throws Throwable;

    //失败可以继续执行
    public static <U> Try<U> ofFailureAble(TrySupplier<U> f) {
        Objects.requireNonNull(f);

        try {
            return Try.successful(f.get());
        } catch (Throwable throwable) {
            return Try.failure(throwable);
        }
    }

    //Try failure
    public static <U> Try<U> failure(Throwable throwable) {
        return new Failure<>(throwable);
    }

    //Try successful
    private static <U> Try<U> successful(U u) {
        return new Success<>(u);
    }

}

class Failure<T> extends Try<T> {
    private final Throwable e;

    public Failure(Throwable e) {
        this.e = e;
    }

    @Override
    public boolean isSuccess() {
        return false;
    }

    @Override
    public T get() throws Throwable {
        throw e;
    }
}

class Success<T> extends Try<T> {
    private final T value;

    public Success(T value) {
        this.value = value;
    }

    @Override
    public boolean isSuccess() {
        return true;
    }

    @Override
    public T get() throws Throwable {
        return value;
    }
}